<template>
    <div class="form-main">
        <el-form ref="formRef" :model="formParams" :rules="rules" label-width="126px" :disabled="disabled">
            <div class="base-info">
                <div class="form-title">基础信息设置</div>
                <el-form-item label="活动名称" prop="activity_name">
                    <el-input
                        v-model.trim="formParams.activity_name"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入活动名称" />
                </el-form-item>
                <el-form-item
                    label="活动有效期"
                    prop="period_type"
                    class="form-radio-item"
                    :class="{ 'activity-time': formParams.period_type === 2 }">
                    <el-radio-group
                        v-model="formParams.period_type"
                        prop="period_type"
                        @change="handlePeriodTypeChange">
                        <el-radio :label="1">永久</el-radio>
                        <el-radio :label="2">固定期限</el-radio>
                    </el-radio-group>
                    <el-form-item v-if="formParams.period_type === 2" class="activity-time-two">
                        <div v-if="formDisabled" class="edit-activity-time">
                            <el-date-picker
                                v-model="formParams.activity_time[0]"
                                disabled
                                type="datetime"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="开始时间" />
                            <el-date-picker
                                v-model="formParams.activity_time[1]"
                                prefix-icon="none"
                                type="datetime"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="结束时间"
                                :disabled-date="disabledDate"
                                :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                                @change="checkActivityTime" />
                        </div>
                        <el-date-picker
                            v-else
                            v-model="formParams.activity_time"
                            type="datetimerange"
                            :disabled-date="disabledDate"
                            :default-time="defaultTime()"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            range-separator="⇀"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            @change="checkActivityTime" />
                    </el-form-item>
                </el-form-item>
                <el-form-item label="活动说明" prop="description">
                    <el-input
                        v-model="formParams.description"
                        style="width: 420px"
                        type="textarea"
                        maxlength="500"
                        :rows="5"
                        show-word-limit
                        placeholder="请输入活动说明" />
                </el-form-item>
            </div>
            <div id="clockInContent" class="rules-info">
                <div class="form-title form-title-top">分流规则设置</div>
                <el-form-item label="引流分组设置" prop="group">
                    <div class="group-list">
                        <div class="table-header">
                            <el-row :gutter="24">
                                <el-col :span="3"><div>序号</div></el-col>
                                <el-col :span="9"><div>分组名称</div></el-col>
                                <el-col :span="9"><div>分组活码</div></el-col>
                                <el-col :span="3"><div>操作</div></el-col>
                            </el-row>
                        </div>
                        <div v-for="(item, index) in formParams.group" :key="index" class="table-cell">
                            <el-form ref="formGroupRef" :model="item" :rules="groupRules" :disabled="disabled">
                                <el-row :gutter="24">
                                    <el-col :span="3">
                                        <div class="group-number">{{ index + 1 }}</div>
                                    </el-col>
                                    <el-col :span="9">
                                        <el-form-item label="" prop="name" class="from-group-name">
                                            <el-input
                                                v-model.trim="item.name"
                                                style="width: 100%"
                                                maxlength="20"
                                                show-word-limit
                                                placeholder="请输入分组名称" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="9">
                                        <el-form-item label="" prop="channel_id">
                                            <el-select
                                                v-model="item.channel_id"
                                                filterable
                                                remote
                                                reserve-keyword
                                                clearable
                                                placeholder="请选择渠道活码"
                                                remote-show-suffix
                                                :remote-method="remoteMethod"
                                                :loading="loading"
                                                @change="selectChange"
                                                @visible-change="visibleChangeChannel($event, index)">
                                                <div
                                                    ref="scrollOptionRef"
                                                    v-infinite-scroll="channelLoad"
                                                    :infinite-scroll-disabled="channelDisabled">
                                                    <el-option
                                                        v-for="item in options"
                                                        :key="item.id"
                                                        :disabled="isSelectUsed(item) || item.disabled"
                                                        :label="item.activity_name"
                                                        :value="item.id" />
                                                </div>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="3">
                                        <el-form-item label="" prop="">
                                            <div
                                                v-if="formParams.group?.length > 1"
                                                class="operate-button"
                                                :class="{ 'operate-button-disabled': disabled }"
                                                @click="onGroupListDel(index)">
                                                删除
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div class="group-list-btn">
                        <el-button
                            :disabled="formParams.group.length >= 20"
                            type="primary"
                            plain
                            @click="onAddGroupList">
                            <el-icon><Plus /></el-icon>
                            <span>添加引流分组</span>
                        </el-button>
                        <div class="group-list-btn-desc">
                            找不到需要的渠道活码？<span
                                :class="{ 'button-disabled': disabled }"
                                @click="onChannelCreated">
                                去创建
                            </span>
                        </div>
                    </div>
                    <div class="drainage-group-text">
                        <div>
                            1）在分流码活动期间，请注意不要将渠道活码删除或提前结束，否则客户进入分组之后将无法匹配到活码客服；
                        </div>
                        <div>
                            2）所选择的渠道活码，在分流码活动开始之后进入的数据都会计入该分流码里，请慎重选择别与其他活动共用，否则其他活动的获客数据也会记录到该分流码活动里；
                        </div>
                        <div>
                            3）系统会自动将其他未开始或正在进行中的分流码活动中使用过的渠道活码标记为不可选择的活码；
                        </div>
                        <div>
                            4）同一个分流码活动不同分组的渠道活码不能相同，已选择过的渠道活码系统会自动标记为不可选择的活码；
                        </div>
                    </div>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, FormInstance } from 'element-plus';
import { defaultTime } from '@/utils/utils';
import { cloneDeep } from 'lodash';
import { shuntCodeChannelList } from '@/api/smartMarketing/drainage/shuntCode';

const route = useRoute();

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {}
    }
});

const formParams = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const disabled = computed(() => {
    return route.query.type == 'look';
});

const formDisabled = computed(() => {
    return formParams.value.activity_status !== 1 && route.query.type == 'edit';
});

/**
 * 分组活码分页加载是否完成禁用
 */
const channelDisabled = computed(() => {
    return options.value.length == pageInfo.total && pageInfo.total;
});

const queryType = ref<any>(route.query.type);

const scrollOptionRef = ref<any>();

/**
 * 表单ref
 */
const formRef = ref<FormInstance>();

/**
 * 分组表单ref
 */
const formGroupRef = ref<FormInstance>();

/**
 * 分组活码列表
 */
const options = ref<any>([]);

/**
 * 编辑分组活码列表
 */
const editOptions = ref<any>([]);

const loading = ref(false);

/**
 * 分组活码
 */
const pageInfo = reactive({
    page: 1,
    page_size: 15,
    total: 0,
    name: ''
});

const excludeGroupList = ref<any>([]);

const disabledDate = (data: any) => {
    // 编辑状态下禁用活动创建之前
    if (formDisabled?.value && formParams.value.created_at) {
        return +data < +new Date(formParams.value.created_at) - 86400000;
    }
    // 86400000 => 一天的时间毫秒
    return +data < +new Date() - 86400000;
};

/**
 * 活动结束时间变更时校验开始和结束时间
 */
const checkActivityTime = () => {
    formRef.value?.validateField(['period_type']);
};

/**
 * 活动有效期类型
 */
const handlePeriodTypeChange = () => {
    formRef.value?.clearValidate(['period_type']);
    // 非编辑页面，不做设置默认值
    if (route.query.type != 'edit') {
        return;
    }
    if (formParams.value.period_type === 2 && !formParams.value.activity_time.length) {
        formParams.value.activity_time = [formParams.value.created_at, null];
    }
};

/**
 * 校验活动名称
 * @param ruls
 * @param value
 * @param callback
 */
const checkActivityName = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请输入活动名称'));
    }

    if (value.length > 20) {
        return callback(new Error('请输入20个文字以内的活动名称'));
    }

    callback();
};

/**
 * 校验活动时间
 * @param ruls
 * @param value
 * @param callback
 */
const checkPeriodType = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请选择活动有效期类型'));
    }

    if (value === 2) {
        const result = formParams.value.activity_time?.every((item: any) => item);
        if (!result || formParams.value.activity_time?.length < 2) return callback(new Error('请选择活动有效期'));

        // 校验结束时间和开始时间
        const [startTime, endTime] = formParams.value.activity_time;
        if (+new Date(startTime) >= +new Date(endTime)) {
            return callback(new Error('活动结束时间不能小于活动开始时间'));
        }
    }
    callback();
};

/**
 * 分组名称
 * @param ruls
 * @param value
 * @param callback
 */
const checkGroupName = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请输入分组名称'));
    }

    if (value.length > 20) {
        return callback(new Error('请输入20个文字以内的分组名称'));
    }
    const list = formParams.value.group.filter(el => el.name == value) || [];
    if (list.length > 1) {
        return callback(new Error('分组名字不能重复'));
    }
    callback();
};

/**
 * 分组活码
 * @param ruls
 * @param value
 * @param callback
 */
const checkGroupChannelId = (ruls: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请选择渠道活码'));
    }
    const list = formParams.value.group.filter((el: any) => el.is_valid == 2);
    if (list.some((el: any) => el.channel_id == value)) {
        return callback(new Error('该活码已被删除/结束'));
    }
    callback();
};

/**
 * 表单校验规则
 */
const rules = reactive({
    activity_name: [{ required: true, validator: checkActivityName, trigger: 'change' }],
    period_type: [{ required: true, validator: checkPeriodType, trigger: 'blur' }],
    group: [{ required: true, message: '', trigger: 'blur' }]
});

const groupRules = reactive({
    name: [{ required: true, validator: checkGroupName, trigger: 'blur' }],
    channel_id: [{ required: true, validator: checkGroupChannelId, trigger: 'change' }]
});

/**
 * 分组活码是否可以使用
 * @param val
 */
const isSelectUsed = (val: any) => {
    if (editOptions.value.some(el => el.channel_id == val.id)) {
        return false;
    }
    return val.is_used == 1;
};

/**
 * 添加引流分组
 * @param evt
 */
const onAddGroupList = (evt: any) => {
    if (disabled.value) return;
    formParams.value.group.push({
        name: '',
        channel_id: ''
    });
};

/**
 * 分组删除index项
 * @param index
 */
const onGroupListDel = (index: any) => {
    if (disabled.value) return;
    formParams.value.group.splice(index, 1);
    setTimeout(() => {
        formGroupRef.value?.map(async (el: any) => {
            await el?.validateField(['name']);
        });
    }, 300);
};

/**
 * 分组活码搜索
 */
const remoteMethod = async (val: any) => {
    if (!pageInfo.name && !val) return;
    pageInfo.page = 1;
    pageInfo.page_size = 15;
    pageInfo.name = val;
    await getShuntCodeChannel();
};

/**
 * 分组活码分页加载
 */
const channelLoad = () => {
    pageInfo.page++;
    getShuntCodeChannel(true);
};

const selectChange = (val: any) => {
    formParams.value.group?.map((el: any) => {
        if (el.channel_id == val) {
            el.is_valid = undefined;
        }
    });
};

/**
 * 分组活码筛选项-展开关闭
 * 处理不同分组-活码不重复
 * @param val true-展开，false-关闭
 * @param index 第几项
 */
const visibleChangeChannel = async (val: boolean, index: number) => {
    excludeGroupList.value = [];
    if (val) {
        excludeGroupList.value = formParams.value.group
            .filter((el: any, idx: number) => idx != index)
            .map((i: any) => i.channel_id);
        loading.value = true;
        options.value = [];
        pageInfo.page = 1;
        await getShuntCodeChannel();
        loading.value = false;
    } else {
        const docList = document.querySelectorAll('.el-select-dropdown__wrap') || [];
        const docItem = docList[index] || {};
        docItem.scrollTop = 0;
    }
};

/**
 * 获取渠道活码
 * @param type 是否是加载
 */
const getShuntCodeChannel = async (type?: boolean) => {
    const params = {
        activity_name: pageInfo.name,
        page: pageInfo.page,
        page_size: pageInfo.page_size
    };
    const res = await shuntCodeChannelList(params);
    const list = res.data || [];
    list.map((el: any) => {
        if (excludeGroupList.value.some((i: any) => i == el.id)) {
            el.disabled = true;
        }
    });
    if (type) {
        options.value = options.value.concat(list);
    } else {
        options.value = list;
    }
    pageInfo.total = res.total || 0;
};

/**
 * 去创建活码，打开新页面
 */
const onChannelCreated = () => {
    if (disabled.value) return;
    window.open('/smartMarketing/drainage/channelCode/newGroupCode?group_id=0');
};

/**
 * 设置分组活码列表，编辑详情-回显使用
 */
const setGroupList = (list: any = []) => {
    editOptions.value = cloneDeep(list);
    list.map((el: any) => {
        options.value.push({
            id: el.channel_id,
            activity_name: el.channel_name
        });
    });
    nextTick(() => {
        formGroupRef.value?.map((el: any) => {
            el?.validateField(['channel_id']);
        });
    });
};

/**
 * 表单校验validate
 */
const validate = async () => {
    try {
        await formRef.value?.validate();
    } catch (err: any) {
        const [[errMessage]]: any = Object.values(err);
        ElMessage.warning({
            grouping: true,
            message: errMessage?.message,
            repeatNum: 1
        });
        return false;
    }
    let errNumber = 0;
    for (let i = 0; i < formGroupRef.value?.length; i++) {
        try {
            await formGroupRef.value?.[i].validate();
        } catch (err: any) {
            const [[errMessage]]: any = Object.values(err);
            let msgErr = errMessage?.message || '';
            if (msgErr == '该活码已被删除/结束') {
                msgErr = msgErr + '，请重新选择';
            }
            ElMessage.warning({
                grouping: true,
                message: msgErr,
                repeatNum: 1
            });
            errNumber++;
        }
    }
    if (errNumber) return false;
    return true;
};

defineExpose({
    validate,
    setGroupList
});
</script>
<style lang="scss" scoped>
.form-main {
    margin: 22px 26px;

    .el-form-item {
        margin-bottom: 24px;
    }

    .form-radio-item {
        margin-bottom: 16px;
    }

    .activity-time-two {
        margin-top: 8px;
        margin-bottom: 8px;
    }

    .el-input {
        width: 420px;
        max-width: 420px;
    }

    :deep(.el-form-item__error) {
        padding-top: 4px;
    }
}

.form-title {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    color: #333;
    font-size: 16px;
    font-family: PingFangSC-Medium, 'PingFang SC';
    font-weight: 500;

    &::before {
        width: 3px;
        height: 16px;
        margin-right: 6px;
        content: '';
        border-radius: 2px;
        background-color: #ff6b00;
    }
}

.form-title-top {
    margin-top: 36px;
}

:deep(.edit-activity-time) {
    display: flex;
    width: 420px;

    .el-input__wrapper {
        border: 1px solid var(--el-input-border-color);
        border-radius: 0;
        box-shadow: none;
    }

    .el-date-editor:first-child {
        .el-input__wrapper {
            border-right: 0;
            border-radius: var(--el-input-border-radius) 0 0 var(--el-input-border-radius);
        }

        &::after {
            position: absolute;
            z-index: 2;
            right: 0;
            content: '-';
            transform: translateX(50%);
            color: #ccc;
        }
    }

    .el-date-editor:last-child {
        .el-input__wrapper {
            border-left: 0;
            border-radius: 0 var(--el-input-border-radius) var(--el-input-border-radius) 0;
        }
    }

    .el-input__prefix {
        margin-right: 6px;
    }
}

.group-list {
    max-width: 876px;

    .table-header {
        padding: 0 16px;
        font-size: 14px;
        font-family: PingFangSC-Medium, 'PingFang SC';
        font-weight: 500;
        color: #585858;
        line-height: 48px;
        background: #f9f9f9;
    }

    .table-cell {
        padding: 0 16px;

        // height: 55px;
        border-bottom: 1px solid #e9e9e9;

        .el-form-item {
            margin: 16px 0;
        }

        .group-number {
            height: 100%;
            display: flex;
            align-items: center;
        }

        .from-group-name {
            margin-right: 42px;
        }

        :deep(.el-form-item__error) {
            padding-top: 2px;
        }

        .operate-button {
            font-size: 14px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: #ff6b00;
            line-height: 32px;
            cursor: pointer;
        }

        .operate-button-disabled {
            cursor: not-allowed;
            opacity: 0.4;
        }
    }
}

.group-list-btn {
    max-width: 876px;
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-list-btn-desc {
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #333;
        line-height: 16px;

        span {
            color: #ff6b00;
            cursor: pointer;
        }

        .button-disabled {
            cursor: not-allowed;
            opacity: 0.4;
        }
    }
}

.group-loading {
    text-align: center;
}

.drainage-group-text {
    max-width: 844px;
    margin-top: 16px;
    padding: 16px;
    background: #fffaf9;
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular, 'PingFang SC';
    font-weight: 400;
    color: #696969;
    line-height: 20px;

    // width: max-content;
}

:deep(.el-button.el-button--primary.is-plain:not(.is-disabled)) {
    --el-button-bg-color: #fff;
    --el-button-border-color: var(--el-color-primary);

    &:hover {
        color: #ff6b00;
        border-color: #ff6b00;
        background-color: #fdefe5;
    }

    &:focus {
        color: #ff6b00;
        background-color: var(--el-button-bg-color);
        border: 1px solid #ffb580;
        outline: none;
    }
}
</style>
